package aygx.integration.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;

/**
 * @author 暗影孤星
 * @date 2022/5/23 15:43
 * @description 定时任务配置
 */
@Slf4j
@Configuration
public class ScheduledConfig implements SchedulingConfigurer {
    @Autowired
    private CustomTaskScheduler customTaskScheduler;
    /**
     * 注册器配置
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {


        // 动态定时
        scheduledTaskRegistrar.addTriggerTask(
                // 任务
                () -> log.info("addTriggerTask,{}", LocalDateTime.now()),
                // 设置执行周期(Trigger)
                triggerContext -> {
                    String cron = "* * * * * ? ";
                    return CronSequenceGenerator.isValidExpression(cron) ? new CronTrigger(cron).nextExecutionTime(triggerContext) : null;
                }
        );

        // 此处实现了SchedulingConfigurer，所以需要重新注入指定ThreadPoolTaskScheduler
        scheduledTaskRegistrar.setTaskScheduler(customTaskScheduler);

        // 直接指定线程数量
        // scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
    }


    //2022-05-23 15:47:25.013  INFO 5572 --- [Scheduled-AYGX1]     : scheduleTest1,2022-05-23T15:47:25.013
    //2022-05-23 15:47:25.014  INFO 5572 --- [Scheduled-AYGX2]     : scheduleTest2,2022-05-23T15:47:25.013
    //2022-05-23 15:47:29.001  INFO 5572 --- [Scheduled-AYGX1]     : scheduleTest1,2022-05-23T15:47:29.001
    //2022-05-23 15:47:29.001  INFO 5572 --- [Scheduled-AYGX2]     : scheduleTest2,2022-05-23T15:47:29.001
    //2022-05-23 15:47:33.003  INFO 5572 --- [Scheduled-AYGX4]     : scheduleTest2,2022-05-23T15:47:33.003
    //2022-05-23 15:47:33.003  INFO 5572 --- [Scheduled-AYGX3]     : scheduleTest1,2022-05-23T15:47:33.003
    //2022-05-23 15:47:37.002  INFO 5572 --- [Scheduled-AYGX5]     : scheduleTest2,2022-05-23T15:47:37.002

    /**
     * 自定义线程池任务
     */
    @Bean
    public TaskScheduler myThreadPoolTaskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 线程池数量
        taskScheduler.setPoolSize(10);
        // 线程前缀CustomTaskScheduler
        taskScheduler.setThreadNamePrefix("Scheduled-AYGX");
        return taskScheduler;
    }
}
